<template>
  <div class="app-container">
    <!--用户数据-->
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          size="small"
          placeholder="输入名称或者邮箱搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-date-picker
          v-model="query.createTime"
          :default-time="['00:00:00', '23:59:59']"
          type="daterange"
          range-separator=":"
          size="small"
          class="date-item"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-select
          v-model="query.state"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in enabledTypeOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
        <rrOperation />
      </div>
      <crudOperation show="" :permission="permission" />
    </div>
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="570px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        size="small"
        label-width="66px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model.number="form.telephone" />
        </el-form-item>
        <el-form-item label="昵称" prop="realname">
          <el-input v-model="form.realname" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item v-permission="['admin']" label="密码">
          <el-input
            v-model="passwordModel"
            style="width: 448px"
            type="password"
            placeholder="不填默认不修改，新增默认123456"
            @input="passwordChange"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender" style="width: 178px">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group
            v-model="form.isfrozen"
            :disabled="form.aid === user.aid"
          >
            <el-radio
              v-for="item in enabledTypeOptions"
              :key="item.key"
              :label="item.key"
              >{{ item.display_name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roleList">
          <el-select
            v-model="form.roleList"
            style="width: 437px"
            multiple
            placeholder="请选择"
            @remove-tag="deleteTag"
            @change="changeRole"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :disabled="adminType !== 1 && item.adminType <= adminType"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          style="margin-bottom: 0"
          label="科室"
          prop="hisDepartmentIds"
        >
          <el-select
            v-model="form.hisDepartmentIds"
            style="width: 437px"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in departments"
              :key="item.hisDepartmentId"
              :label="item.departmentName"
              :value="item.hisDepartmentId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2"
          type="primary"
          @click="crud.submitCU"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data[crud.listName]"
      style="width: 100%"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="username"
        label="用户名"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="realname"
        label="昵称"
      />
      <el-table-column prop="roleList" label="角色级别">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.roleList" :key="item.index">{{
            scope.row.roleList.length - 1 === index
              ? item.roleName
              : item.roleName + "、"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="departmentList" label="科室">
        <template slot-scope="scope">
          <span
            v-for="(item, index) in scope.row.departmentList"
            :key="item.index"
            >{{
              scope.row.departmentList.length - 1 === index
                ? item.departmentName
                : item.departmentName + "、"
            }}</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别">
        <template slot-scope="scope">
          {{
            scope.row.gender === 1
              ? "男"
              : scope.row.gender === 2
              ? "女"
              : "未知"
          }}
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        prop="telephone"
        width="100"
        label="电话"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        width="135"
        prop="email"
        label="邮箱"
      />
      <el-table-column label="状态" align="center" prop="isfrozen">
        <template slot-scope="scope">
          <el-tooltip
            :content="scope.row.isfrozen === 0 ? '激活' : '冻结'"
            placement="top"
          >
            <el-switch
              v-model="scope.row.isfrozen"
              :active-value="0"
              :inactive-value="1"
              :disabled="user.aid === scope.row.aid"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.isfrozen)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        prop="createtime"
        width="135"
        label="创建日期"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-permission="['admin', 'auth/update', 'auth/delete']"
        label="操作"
        width="115"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
            :disabled-dle="scope.row.aid === user.aid"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudUser, { getDepartList, updateStatus } from "@/api/system/user";
// import { isvalidPhone } from '@/utils/validate'
import { list, getLevel } from "@/api/system/role";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { mapGetters } from "vuex";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { kke } from "@/utils/rsaEncrypt";
let userRoles = [];
const defaultForm = {
  aid: null,
  username: null,
  realname: null,
  gender: 1,
  email: null,
  isfrozen: 0,
  roleList: [],
  telephone: null,
  password: null,
  hisDepartmentIds: [],
};
export default {
  name: "User",
  components: { crudOperation, rrOperation, udOperation, pagination },
  cruds() {
    return CRUD({
      title: "用户",
      url: "admin/auth/list",
      crudMethod: { ...crudUser },
      optShow: { reset: true, add: true, edit: false, del: false, download: false },
    });
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    // 自定义验证
    // const validPhone = (rule, value, callback) => {
    //   if (!value) {
    //     callback(new Error('请输入电话号码'))
    //   } else if (!isvalidPhone(value)) {
    //     callback(new Error('请输入正确的11位手机号码'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      height: document.documentElement.clientHeight - 180 + "px;",
      passwordModel: "",
      adminType: 3,
      roles: [],
      departments: [],
      defaultProps: { children: "children", label: "name", isLeaf: "leaf" },
      permission: {
        add: ["admin", "auth/add"],
        edit: ["admin", "auth/update"],
        del: ["admin", "auth/delete"],
        export: ["admin", "auth/export"],
      },
      enabledTypeOptions: [
        { key: "0", display_name: "激活" },
        { key: "1", display_name: "冻结" },
      ],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        realname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: false, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        telephone: [{ required: false, trigger: "blur" }],
        roleList: [{ required: true, message: "请选择角色", trigger: "blur" }],
        hisDepartmentIds: [{ required: true, message: "请选择科室", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapGetters(["user"]),
  },
  created() {
    this.crud.msg.add = "新增成功";
  },
  mounted: function () {
    const that = this;
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + "px;";
    };
  },
  methods: {
    changeRole(value) {
      userRoles = [];
      value.forEach(function (data, index) {
        const role = { id: data };
        userRoles.push(role);
      });
    },
    passwordChange(val) {
      if (val !== null && val !== "") {
        this.form.password = kke("admin", val);
      } else {
        this.form.password = null;
      }
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud);
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud);
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = [];
      userRoles.forEach(function (role, index) {
        initRoles.push(role.id);
      });
      crud.form.roleList = initRoles;
    },
    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value) {
          userRoles.splice(index, value);
        }
      });
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles();
      this.getDepartments();
      this.getRoleLevel();
      form.isfrozen = form.isfrozen.toString();
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      userRoles = [];
      const roles = [];
      form.roleList.forEach(function (role, index) {
        roles.push(role.id);
        // 初始化编辑时候的角色
        const rol = { id: role.id };
        userRoles.push(rol);
      });
      form.hisDepartmentIds = form.departmentList.map(
        (item) => item.hisDepartmentId
      );
      form.roleList = roles;
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.roleList.length === 0) {
        this.$message({
          message: "角色不能为空",
          type: "warning",
        });
        return false;
      }
      crud.form.roleList = userRoles;
      return true;
    },
    // 改变状态
    changeEnabled(data, val) {
      let statusObj = {};
      this.enabledTypeOptions.forEach(function (item, index) {
        if (item.key === val.toString()) {
          statusObj = item;
        }
      });
      this.$confirm(
        '此操作将 "' +
          statusObj.display_name +
          '" ' +
          data.username +
          ", 是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updateStatus({
              aid: data.aid,
              isfrozen: data.isfrozen
            })
            .then((res) => {
              this.crud.notify(
                statusObj.display_name + "成功",
                CRUD.NOTIFICATION_TYPE.SUCCESS
              );
            })
            .catch(() => {
              data.isfrozen = data.isfrozen === 0 ? 1 : 0;
            });
        })
        .catch((err) => {
          console.log(err)
          data.isfrozen = data.isfrozen === 0 ? 1 : 0;
        });
    },
    // 获取弹窗内角色数据
    getRoles() {
      list({ pageIndex: 1, pageSize: 1000 })
        .then((res) => {
          this.roles = res.content;
        })
        .catch(() => {});
    },
    // 获取弹窗内科室数据
    getDepartments() {
      getDepartList({ page: 1, size: 1000 })
        .then((res) => {
          this.departments = res.content;
        })
        .catch(() => {});
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel()
        .then((res) => {
          this.adminType = res.content;
        })
        .catch(() => {});
    },
    checkboxT(row, rowIndex) {
      return row.aid !== this.user.aid;
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .vue-treeselect__control,
/deep/ .vue-treeselect__placeholder,
/deep/ .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
